//
//  PACreateDirectionConfigVC.m
//  iCon
//
//  Created by leon on 2018/11/13.
//  Copyright © 2018年 leon. All rights reserved.
//

#import "PACreateDirectionConfigVC.h"
#import "ChartConfig.h"
#import "PAWebSocketManager.h"
#import "PAChartConfigManager.h"
#import "PAGroupManager.h"
#import "PAAccountManager.h"
@implementation PACreateDirectionConfigVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"Create Direction Chart";
////    [self initializeForm];
//    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(configData:)];
}

-(id)init
{
    self = [super init];
    if (self) {
        self.title = @"Create Direction Chart";
        //    [self initializeForm];
        self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(configData:)];
        [self initializeForm];
    }
    return self;
}

-(void)initializeForm{
    XLFormDescriptor * form;
    XLFormSectionDescriptor * section;
    XLFormRowDescriptor * row;
    
    form = [XLFormDescriptor formDescriptor];
    form.rowNavigationOptions = XLFormRowNavigationOptionNone;
    //    form.assignFirstResponderOnShow = YES;
    section = [XLFormSectionDescriptor formSectionWithTitle:nil];
//
//    XLFormRowDescriptor *infoRowDescriptor = [XLFormRowDescriptor formRowDescriptorWithTag:@"title"rowType:XLFormRowDescriptorTypeInfo];
//    infoRowDescriptor.title = @"title";
//    infoRowDescriptor.value = @"title";
//    [section addFormRow:infoRowDescriptor];
    // Name
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"chartName" rowType:XLFormRowDescriptorTypeText title:@"chartName"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value =@"";
//    row.required = YES;
    [section addFormRow:row];
    
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"startTime" rowType:XLFormRowDescriptorTypeDate title:@"startTime"];
    row.required = YES;
    row.value = [NSDate new];
    [section addFormRow:row];
    
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"endTime" rowType:XLFormRowDescriptorTypeDate title:@"endTime"];
    [section addFormRow:row];
    
    // MaxRecords
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"maxRecords" rowType:XLFormRowDescriptorTypeNumber title:@"maxRecords"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = @900000;
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"maxHistoricalPoints" rowType:XLFormRowDescriptorTypeNumber title:@"maxHistoricalPoints"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = @10000;
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"orderby" rowType:XLFormRowDescriptorTypeSelectorPush title:@"Orderby"];
    row.selectorOptions = @[@"DESC",@"ASC"];
    row.value = @"DESC";
    
    [section addFormRow:row];
    
    // Name
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"directionname" rowType:XLFormRowDescriptorTypeText title:@"directionname"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value =@"";
    row.required = YES;
    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"quarter" rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"quarter"];
    NSDictionary *metadata = [PAAppContext sharedInstance].metaData;
    NSString *quarterStr = metadata[@"Quarter"];
    if(quarterStr!=nil && ![quarterStr isEqualToString:@""]){
        row.selectorOptions = [quarterStr componentsSeparatedByString:@","];
        row.value =[quarterStr componentsSeparatedByString:@","];
    }else{
        row.selectorOptions =@[];
    }
    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"ctd" rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"ctd"];

    NSString *ctdStr = metadata[@"CTD"];
    if(ctdStr!=nil && ![ctdStr isEqualToString:@""]){
        row.selectorOptions = [ctdStr componentsSeparatedByString:@","];
        row.value =[ctdStr componentsSeparatedByString:@","];
    }else{
        row.selectorOptions =@[];
    }
    [section addFormRow:row];
    
    // Name
//    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"ctd" rowType:XLFormRowDescriptorTypeText title:@"ctd"];
//    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
//    row.value =@"";
////    row.required = YES;
//    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"business.hours" rowType:XLFormRowDescriptorTypeMultipleSelector title:@"businesshours"];
    row.selectorOptions = @[@"6:30-23:00",
                            @"8:00-18:00",
                            @"7:00-11:45,13:30-18:00",
                            @"7:30-11:30,13:00-15:16",
                            @"8:00-12:00,13:00-18:00",
                            @"9:00-11:45,13:00-15:33",
                            @"9:00-12:00,13:00-17:00",
                            @"9:00-12:00,13:00-17:30",
                            @"9:14-11:30,13:00-15:15"];
    row.value = @[@"8:00-12:00,13:00-18:00"];
    
    [section addFormRow:row];
    
    [form addFormSection:section];
    
    self.form = form;
}



-(void)configData:(UIBarButtonItem *)buttonItem
{
    if (![self validateDatas]) {
        return;
    }
    
    XLFormRowDescriptor * row = [self.form formRowWithTag:@"chartName"];
    
    NSDictionary *dic = [self formValues];
    NSMutableDictionary *mdic = [dic mutableCopy];
    NSArray *hours =dic[@"business.hours"];
    mdic[@"business.hours"] = [hours componentsJoinedByString: @","];
    if ([dic[@"chart.ownaxis"] isKindOfClass:[NSNull class]] || [dic[@"chart.ownaxis"] isEqual:@0]) {
        mdic[@"chart.ownaxis"] = @NO;
    }else{
        mdic[@"chart.ownaxis"] = @YES;
        
    }
    if ([dic[@"window.frameless"] isKindOfClass:[NSNull class]] || [dic[@"window.frameless"] isEqual:@0]) {
        mdic[@"window.frameless"] = @NO;
    }else{
        mdic[@"window.frameless"] = @YES;
        
    }
    
    if (dic[@"startTime"]!=nil && ![dic[@"startTime"] isKindOfClass:[NSNull class]]) {
        //mdic[@"startTime"] = [dic[@"startTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
       double t =  [dic[@"startTime"] timeIntervalSince1970];
        mdic[@"startTime"] = [NSNumber numberWithDouble:t*1000];
    }else{
//        mdic[@"startTime"] = [[NSDate new] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
        double t =  [[NSDate new] timeIntervalSince1970];
        mdic[@"startTime"] = [NSNumber numberWithDouble:t*1000];
    }
    if (dic[@"endTime"]!=nil && ![dic[@"endTime"] isKindOfClass:[NSNull class]]) {
      
        double t =  [dic[@"endTime"] timeIntervalSince1970];
        mdic[@"endTime"] = [NSNumber numberWithDouble:t*1000];
//      mdic[@"endTime"] = [dic[@"endTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
    }else{
        mdic[@"endTime"] = @"";
    }
    if(mdic[@"quarter"] == nil || [mdic[@"quarter"] isKindOfClass:[NSNull class]]){
         [mdic removeObjectForKey:@"quarter"];
    }else{
        mdic[@"quarter"]  = [dic[@"quarter"] componentsJoinedByString:@","];
    }
    if(mdic[@"ctd"] == nil || [mdic[@"ctd"] isKindOfClass:[NSNull class]]){
        [mdic removeObjectForKey:@"ctd"];
    }else{
        mdic[@"ctd"]  = [dic[@"ctd"] componentsJoinedByString:@","];
    }

    NSLog(@"%@",mdic);
    if(row.value == nil || [row.value isEqualToString: @""]){
        row.value = dic[@"directionname"];
    }
    mdic[@"directionname"] = [dic[@"directionname"] lowercaseString];
    
    if(![dic[@"endTime"] isKindOfClass:[NSNull class]] && ![mdic[@"endTime"] isEqualToString:@""]){
        long long t = [mdic[@"endTime"] longLongValue] - 7776000L*1000L;
        t = MAX([mdic[@"startTime"] longLongValue],t);
        mdic[@"startTime"] = [NSNumber numberWithLongLong: t];
    }else{
        long long t =  ([[NSDate new] timeIntervalSince1970] - 7776000L)*1000L;
        t = MAX([mdic[@"startTime"] longLongValue],t);
        mdic[@"startTime"] = [NSNumber numberWithLongLong: t];
    }
    
    ChartConfig *chartConfig = [ChartConfig new];
    NSMutableDictionary *mConfig = [NSMutableDictionary new];
    
    mConfig[CONFIG_KEY_CONFIGSOURCE] = w_cofingSource;
    mConfig[CONFIG_KEY_HOST] = [PAAppContext sharedInstance].w_host;
    mConfig[CONFIG_KEY_PORT] = [NSNumber numberWithLong:[PAAppContext sharedInstance].w_port];
    mConfig[CONFIG_KEY_TYPE] = @"command";
    mConfig[CONFIG_KEY_COMMAND] = @"config";
    mConfig[CONFIG_KEY_CHARTNAME] =  row.value; 
    mConfig[CONFIG_KEY_TITLE] = row.value;
    mConfig[CONFIG_KEY_GRAPHTYPE] = w_graphType;
    mConfig[CONFIG_KEY_APPID] =[PAAppContext sharedInstance].appid;
    mConfig[@"maxHistoricalPoints"] = mdic[@"maxHistoricalPoints"];
    chartConfig.chartName = row.value;
    chartConfig.config = mConfig;
    mConfig[CONFIG_KEY_RANGECONFIG] =  @{@"columnNames":@[@"dummy"], @"rowNames":@[@"dummy"], @"rangeName": @"dummy",@"orderby":dic[@"orderby"],@"maxRecords":dic[@"maxRecords"],@"startTime":mdic[@"startTime"],@"endTime":mdic[@"endTime"]};
    
//    mdic[@"mergestrategy"] = @"INTERSECT";
//    mdic[@"ohlc.chartType"] = @"OHLC";
//    mdic[@"ohlc.grouping.relaxed"] = @YES;
//    mdic[@"ohlc.period"] = @"1h";
//    mdic[@"ohlc.start"] = @"-5d";
    
    [mdic removeObjectForKey:@"startTime"];
    [mdic removeObjectForKey:@"endTime"];
    [mdic removeObjectForKey:@"orderby"];
    [mdic removeObjectForKey:@"maxRecords"];
    [mdic removeObjectForKey:@"chartName"];
    
    mConfig[@"parameters"] = mdic;
    //如果本地已经有该config了，则提醒用户
    if ([[PAAppContext sharedInstance].chartNames containsObject:row.value]) {
        
        [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
            if (buttonIndex==1) {
                
                [self processChartConfig:chartConfig isAdd:NO];
                
                
            }else if (buttonIndex==0){
                
                
            }
            
        } title:@"Conifrim Chart" message:@"Already have the chart,are you meaning to override it?" cancelButtonName:@"cancel" otherButtonTitles:@"override", nil];
        
    }else{
        
        
        [self processChartConfig:chartConfig isAdd:YES];
        
    }
    
}

- (void)processChartConfig:(ChartConfig *)chartConfig isAdd:(BOOL) isAdd
{
    //1.发送config
//    if(![[PAWebSocketManager sharedInstance] sendMsg:chartConfig.config.mj_JSONString]) return;
    
    //2.保存到currentChart
    BOOL isUpdate = [PAChartConfigManager saveChartConfig:chartConfig];
    
    //3.查看是否选中群组，如果选中，则添加到群组中
    NSString *groupName = [PAAccountManager loadCurrentGroupName];
    if (groupName!=nil &&![groupName isEqualToString:@""]) {
        
        [PAGroupManager addChartConfig:chartConfig.chartName toGroup:groupName];
    }else{
        [PAGroupManager updateGroup:@"Default"  withChartNames:@[chartConfig.chartName]];
    }
    //4.新增或者修改chartConfigs
    if (isAdd) {
        [[PAAppContext sharedInstance].chartConfigs addObject:chartConfig];
    }else{
        NSInteger index = [[PAAppContext sharedInstance].chartNames indexOfObject:chartConfig.chartName];
        [[PAAppContext sharedInstance].chartConfigs replaceObjectAtIndex:index withObject:chartConfig];
    }
    //5.通知collectionview 添加graph
    if (isUpdate) {
        [[NSNotificationCenter defaultCenter] postNotificationName:PACurrentChartUpdateNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
    }else{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:PAChartListVCItemClickNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
    }
    
    
    //6.
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModePrimaryHidden;
}

-(BOOL)validateDatas{
    NSArray * array = [self formValidationErrors];
    if (array ==nil || array.count<1) {
        return YES;
    }else{
        [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            XLFormValidationStatus * validationStatus = [[obj userInfo] objectForKey:XLValidationStatusErrorKey];
            UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:[self.form indexPathOfFormRow:validationStatus.rowDescriptor]];
            [cell shake];
            
        }];
        return NO;
    }
    
    
    
}

@end
